<template>
  <uploader
    ref="uploader"
    :options="finalOptions"
    :file-status-text="statusText"
    :show-success-files="showSuccessFiles"
    :single-flag="singleFlag"
    :auto-start="autoStart"
    :show-list-flag="showListFlag"
    @file-complete="fileComplete"
    @file-added="fileAdded"
  />
</template>

<script>
import Uploader from '@/components/SimpleUploader'

export default {
  components: {
    Uploader
  },
  props: {
    options: {
      type: Object,
      required: false,
      default() {
        return {}
      }
    },
    singleFlag: {
      type: Boolean,
      default: false
    },
    autoStart: {
      type: Boolean,
      default: true
    },
    // 是否显示文件列表
    showListFlag: {
      type: Boolean,
      default: true
    },
    entityType: {
      type: String,
      required: true

    },
    entityId: {
      type: String,
      default: '',
      required: true
    },
    moduleCode: {
      type: String,
      required: true
    },
    showSuccessFiles: {
      type: Boolean,
      default: false,
      required: false
    },
    serverUrl: {
      type: String,
      default: '',
      required: true
    }
  },
  data() {
    return {
      defaultOptions: {
        withCredentials: true,
        target: process.env.VUE_APP_BASE_API + this.serverUrl,
        testChunks: false,
        maxChunkRetries: 3,
        chunkSize: 10485760,
        query: {
          entityType: this.entityType,
          entityId: this.entityId,
          moduleCode: this.moduleCode
        },
        generateUniqueIdentifier: () => {
          // 业务主键+时间戳最大限度降低并发冲突发生的概率
          return this.entityId + new Date().getTime()
        },
        parseTimeRemaining(timeRemaining, parsedTimeRemaining) {
          return parsedTimeRemaining
            .replace(/\syears?/, '年')
            .replace(/\days?/, '天')
            .replace(/\shours?/, '时')
            .replace(/\sminutes?/, '分')
            .replace(/\sseconds?/, '秒')
        }
      },
      statusText: {
        success: '100%',
        error: '失败',
        uploading: '上传中',
        paused: '暂停中',
        waiting: '等待中'
      }
    }
  },
  computed: {
    finalOptions: function () {
      const opts = Object.assign(this.defaultOptions, this.options)
      return opts
    }
  },
  watch: {
    entityId: function () {
      this.$refs.uploader.options.query.entityId = this.entityId
    }
  },
  methods: {
    fileComplete(file) {
      this.$emit('fileComplete', file)
    },
    fileAdded(file) {
      this.$emit('fileAdded', file)
    }
  }
}
</script>
